#include "CloudiskServer.h"
#include "CryptoUtil.h"
#include "workflow/MySQLResult.h"
#include "nlohmann/json.hpp"
#include "wfrest/PathUtil.h"
#include "HashUtil.h"
#include <map>
#include <string>
#include <sstream>
#include <fstream>
using namespace wfrest;
using namespace protocol;
using std::cout;
using std::endl;
using std::map;
using std::string;
using std::istringstream;
using std::ifstream;
using std::ostringstream;


//用户注册路由
void CloudiskServer::register_signup_modules(){
    m_server.POST("/user/signup",[](const HttpReq *req,HttpResp *resp){
        if(req->content_type()!=APPLICATION_URLENCODED){
            resp->set_status(HttpStatusBadRequest);
            return;
        }

        //获取用户输入
        map<string,string> userinfo = req->form_kv();
        string username = userinfo["username"];
        string password = userinfo["password"];

        //生成新用户盐值及其hashword
        string salt = CryptoUtil::generate_salt();
        string hashword = CryptoUtil::hash_password(password,salt);
        //设置mysql查询语句
        string sql_query = "insert into tbl_user (username,password,salt) values ('" 
        + username + "','" + hashword + "','" + salt + "');";

        //MYSQL任务进行查询
        resp->MySQL(mysql_url,sql_query,[resp](MySQLResultCursor *cursor){
            if(cursor->get_cursor_status()==MYSQL_STATUS_OK && cursor->get_affected_rows()==1){
                resp->set_status(HttpStatusOK);
                resp->String("SUCCESS");
            }else{
                resp->set_status(HttpStatusBadRequest);
                resp->String("Already exist");
            }
        });
    });
}

//用户登录路由
void CloudiskServer::register_signin_modules(){
    m_server.POST("/user/signin",[](const HttpReq *req,HttpResp *resp){
        if(req->content_type()!=APPLICATION_URLENCODED){
            resp->set_status(HttpStatusBadRequest);
            return;
        }

        map<string,string> userinfo = req->form_kv();
        string username = userinfo["username"];
        string password = userinfo["password"];

        //查询数据库中对应用户名的信息
        string sql_query = "select * from tbl_user where username = '" + username + "';";
        std::cout << "[SQL]" << sql_query << std::endl;
        resp->MySQL(mysql_url,sql_query,[resp,password](MySQLResultCursor *cursor){
            if(cursor->get_cursor_status()!=MYSQL_STATUS_GET_RESULT || cursor->get_rows_count()!=1){
                resp->set_status(HttpStatusBadRequest);
                resp->String("username input wrong!");
            }
            
            //获取对应用户名的信息
            map<string,MySQLCell> record;
            if(cursor->fetch_row(record)){
                User user;
                user.id = record["id"].as_int();
                user.username = record["username"].as_string();
                user.hashcode = record["password"].as_string();
                user.salt = record["salt"].as_string();
                user.createdAt = record["created_At"].as_string();

                if(CryptoUtil::hash_password(password,user.salt)==user.hashcode){
                    string token = CryptoUtil::generate_token(user);
                    nlohmann::json retMsg;
                    retMsg["data"]["Token"] = token;
                    retMsg["data"]["Username"] = user.username;
                    retMsg["data"]["Location"] = "/static/view/home.html";
                    resp->set_status(HttpStatusOK);
                    //resp->set_header_pair("Content-Type", "application/json");
                    resp->String(retMsg.dump());
                    return;
                }
            }
            resp->set_status(HttpStatusBadRequest);
            resp->String("password Input wrong！");
        });
    });
}